package manager

import (
	"crypto/md5"
	"fmt"
	"github.com/tianjigames/fairy/template"
	"github.com/topfreegames/pitaya"
	"github.com/topfreegames/pitaya/logger"
	"sync"
)

var (
	GMAccountManager *gMAccountManager
	gmAccountMangerOnce sync.Once
)

/**
gm账户管理器
 */
type gMAccountManager struct {
	BaseManager
	gMAccountInfoMap map[string]*template.GMAccount
}

func NewGMAccountManager() *gMAccountManager {
	gmAccountMangerOnce.Do(func() {
		GMAccountManager = &gMAccountManager{
			gMAccountInfoMap: map[string]*template.GMAccount{},
		}
	})
	return GMAccountManager
}

func (p *gMAccountManager) Init()  {
	accountList := pitaya.GetTemplates(template.GMAccountKey)
	if accountList != nil && len(accountList) > 0 {
		for _,v := range accountList {
			account := v.(*template.GMAccount)
			p.gMAccountInfoMap[account.AccountName] = account
		}
	}
}

/**
判断某个账户是否为白名单账户
 */
func (p *gMAccountManager) IsGMAccount(accountName string) bool {
	 _,ok := p.gMAccountInfoMap[accountName]
	 return ok
}

/**
获取某个GM账户
 */
func (p *gMAccountManager) GetGMAccountBase(accountName string) *template.GMAccount {
	if p.IsGMAccount(accountName) {
		return p.gMAccountInfoMap[accountName]
	}else {
		return nil
	}
}

/**
检查账户名是否存在，不存在 创建账户
 */
func (p *gMAccountManager) CheckInsertGMAccount(accountName,channelId,appId string) error {
	accountInfo := p.GetGMAccountBase(accountName)
	if accountInfo != nil {
		dbAccountData,err := PlayerManager.GetAccountDataByUsernameAndChannelIdAndAppId(accountName,channelId,appId)
		if err != nil {
			logger.Log.Errorf("[GMAccountManager] CheckInsertGMAccount failed,error=%s",err.Error())
			return err
		}

		if dbAccountData == nil {
			_,err = PlayerManager.CreateLocalAccount(accountName,channelId,fmt.Sprintf("%x",md5.Sum([]byte(accountInfo.Password))),"0","0",appId)
			if err != nil {
				logger.Log.Errorf("[GMAccountManager] CheckInsertGMAccount failed,error=%s",err.Error())
				return err
			}
		}
	}

	return nil
}


